package com.echo.yixiaowu.main.page.home

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp

@Stable
class CollapsingToolbarState(
    private val listState: LazyListState,
    private val initialHeaderHeightPx: Float
) {
    /**
     * 头部需要向上平移的距离（一个负值）。
     */
    val headerOffset: Float by derivedStateOf {
        if (listState.firstVisibleItemIndex == 0) {
            // 限制最大偏移量，防止过度滚动
            -listState.firstVisibleItemScrollOffset.toFloat().coerceAtMost(initialHeaderHeightPx)
        } else {
            -initialHeaderHeightPx
        }
    }
}

@Composable
fun rememberCollapsingToolbarState(
    listState: LazyListState,
    headerHeight: Dp,
): CollapsingToolbarState {
    val headerHeightPx = with(LocalDensity.current) { headerHeight.toPx() }

    // 使用 remember，并以 listState 和 headerHeightPx 作为 key
    return remember(listState, headerHeightPx) {
        CollapsingToolbarState(listState, headerHeightPx)
    }
}